/**
 * Copyright 2018 orivil.com. All rights reserved.
 * Use of this source code is governed by a MIT-style
 * license that can be found at https://mit-license.org.
 */

package model

import (
	"strings"
	"gitee.com/tugoer/orivil/bundles/db"
)

var articleHtml = "views/article.gohtml"

type Domain struct {
	ID int
	Domain string `gorm:"index"`
	WeChatID int `gorm:"index"`
	IndexFile string
	Password string
	ServeDomain string `gorm:"-" desc:"管理平台域名，由前端提供"`
	CountScript string
}

func (d *Domain)Create() error {
	return db.Gorm.Create(d).Error
}

//func UploadFiles(domain, serveDomain, indexFile, password string, wechatID int) error {
//	cookies, err := http.Login(domain, indexFile, password)
//	if err != nil {
//		return err
//	}
//	dir, err := http.GetSiteDir(domain, indexFile, cookies)
//	if err != nil {
//		return err
//	}
//	wechat := GetWeChatByID(wechatID)
//	err = http.PostFile(domain, indexFile, wechat.MPFile, dir, wechat.MPText, cookies)
//	if err != nil {
//		return err
//	}
//	err = http.PostFile(domain, indexFile, wechat.MPFile, dir, wechat.MPText, cookies)
//	if err != nil {
//		return err
//	}
//	data, err := ioutil.ReadFile(articleHtml)
//	if err != nil {
//		return err
//	}
//	data = bytes.Replace(data, []byte("{{.domain}}"), []byte(serveDomain), 1)
//	return http.PostFile(domain, indexFile, "article.html", dir, string(data), cookies)
//}
//
//func RenameIndex(domain, oldFile, newFile, oldPassword, newPassword string) error {
//	cookies, err := http.Login(domain, oldFile, oldPassword)
//	if err != nil {
//		return err
//	}
//	dir, err := http.GetSiteDir(domain, oldFile, cookies)
//	if err != nil {
//		return err
//	}
//	return http.RenameIndex(domain, dir, oldFile, newFile, newPassword, cookies)
//}

func (d *Domain)Save() error {
	//if d.ServeDomain != "" {
	//	err := UploadFiles(d.Domain, d.ServeDomain, d.IndexFile, d.Password, d.WeChatID)
	//	if err != nil {
	//		return err
	//	}
	//}
	return db.Gorm.Save(d).Error
}

func (d *Domain)Delete() error {
	return db.Gorm.Delete(d).Error
}

func QueryDomain(wechatID int) (ds []*Domain, err error) {
	err = db.Gorm.Where("we_chat_id=?", wechatID).Find(&ds).Error
	return
}

func GetDomainByID(id int) (domain *Domain, err error) {
	domain = &Domain{ID: id}
	err = db.Gorm.First(domain).Error
	return
}

func GetDomainByHost(host string) (domain *Domain, err error) {
	domain = &Domain{}
	if !strings.HasPrefix(host, "http") {
		host = "http://" + host
	}
	err = db.Gorm.Where("domain=?", host).First(domain).Error
	return
}
